package com.mlming.springboot.handler;

import com.mlming.springboot.enums.ResponseEnum;
import com.mlming.springboot.exceptions.UserLoginException;
import com.mlming.springboot.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局异常处理类
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 对用户状态未登录时抛出的异常的处理
     * @return
     */
    @ExceptionHandler(UserLoginException.class)
    @ResponseBody //返回json格式给前端,所以说: 其实SpringMVC的异常处理器就相当于一个Controller
    @ResponseStatus(HttpStatus.FORBIDDEN) // 响应的状态码,默认是200
    public ResponseVo userLoginExceptionHandler() {
        // 向浏览器返回错误信息的vo对象
        return ResponseVo.error(ResponseEnum.NEED_LOGIN);
    }

    /**
     * 对Controller方法参数传递错误的统一处理
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseVo userLoginExceptionHandler(MethodArgumentNotValidException e) {
        // 获取到BindingResult类对象,返回错误信息
        BindingResult bindingResult = e.getBindingResult();
        return ResponseVo.error(ResponseEnum.PARAMS_ERROR,bindingResult);
    }

    /**
     * 对RuntimeException统一异常处理
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseVo runtimeExceptionHandler(Exception e) {
        return ResponseVo.error(ResponseEnum.ERROR,e.getMessage());
    }

    /**
     * 对InterruptedException统一异常处理
     * @return
     */
    @ExceptionHandler(InterruptedException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseVo interruptedExceptionHandler(Exception e) {
        return ResponseVo.error(ResponseEnum.ERROR,"服务器端繁忙");
    }

}
